package cn.leida.ruoyi.system.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.leida.ruoyi.common.core.page.PageDomain;
import cn.leida.ruoyi.common.core.page.TableSupport;
import cn.leida.ruoyi.system.bean.BaseSqlBean;
import com.alibaba.fastjson2.JSONObject;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
import org.hibernate.query.sql.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lei
 * @create 2025-03-06 10:48
 */
public class SysJdbcService {

    @PersistenceContext
    private EntityManager entityManager;

    /**
     * 根据sql 返回long(统计数据使用)
     *
     * @param sql    统计sql
     * @param params 参数
     * @return 数量
     */
    public long queryForLong(String sql, List<Object> params) {
        long total = 0;
        Query totalQuery = entityManager.createNativeQuery(sql);
        System.out.println(sql);
        initParams(totalQuery, params);
        List<?> resultList = totalQuery.getResultList();

        if (!resultList.isEmpty()) {
            String totalStr = resultList.get(0) + "";
            if (NumberUtil.isLong(totalStr)) {
                return NumberUtil.parseLong(totalStr);
            }
        }
        return total;
    }

    /**
     * 根据sql 返回long(统计数据使用)
     *
     * @param sql 统计sql
     * @return 数量
     */
    public long queryForLong(String sql) {
        return queryForLong(sql, new ArrayList<>());
    }

    // 初始化参数
    private void initParams(Query totalQuery, List<Object> params) {
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                totalQuery.setParameter(i + 1, params.get(i));
            }
        }
    }

    /**
     * 根据sql查询 JSONObject
     *
     * @param sql    查询语句
     * @param params 参数
     * @return 结果
     */
    public List<JSONObject> queryForList(String sql, List<Object> params) {
        return queryForList(sql, params, null);
    }

    /**
     * 分页参数数据
     *
     * @param sql      查询sql
     * @param params   参数
     * @param pageable 分页参数
     * @return 结果
     */
    public List<JSONObject> queryForList(String sql, List<Object> params, Pageable pageable) {

        Query contentQuery = entityManager.createNativeQuery(sql);
        initParams(contentQuery, params);
        // 查询为简单map
        contentQuery.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        // 分页参数
        if (pageable != null) {
            contentQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
            contentQuery.setMaxResults(pageable.getPageSize());
        }

        List<Object> results = contentQuery.getResultList();
        List<JSONObject> resultDatas = new ArrayList<>();
        if (results != null && !results.isEmpty()) {
            //  map 转对象
            for (Object obj : results) {
                JSONObject jsonObject = JSONObject.from(obj);
                resultDatas.add(jsonObject);
            }
        }
        return resultDatas;
    }

    /**
     * 根据sql查询 JSONObject
     *
     * @param sql 查询语句
     * @return 结果
     */
    public List<JSONObject> queryForList(String sql) {
        return queryForList(sql, new ArrayList<>());
    }

    /**
     * 分页参数
     *
     * @param sqlBean  sql语句
     * @param pageable 分页参数
     * @return 结果
     */
    public Page<JSONObject> queryPage(BaseSqlBean sqlBean, Pageable pageable) {
        // 总记录数
        System.out.println();
        System.out.println();
        System.out.println(sqlBean.countSql());
        System.out.println();
        System.out.println();
        long total = queryForLong(sqlBean.countSql(), sqlBean.params());

        System.out.println(sqlBean.selectSql());
        System.out.println();
        System.out.println();
        // 分页数据
        List<JSONObject> results = queryForList(sqlBean.selectSql(), sqlBean.params(), pageable);

        return new PageImpl<>(results, pageable, total);
    }

    public Pageable pageable() {
        PageDomain pageReq = TableSupport.buildPageRequest();
        return PageRequest.of(pageReq.getPageNum() - 1, pageReq.getPageSize());
    }

    /**
     * 根据 dataId 查询long列表
     *
     * @param sql select xxx as dataId from ...
     * @param params 参数
     * @return dataIds
     */
    public  List<Long> queryDataIds(String sql,List<Object> params) {
        List<JSONObject> jsonList = this.queryForList(sql.toString(), params);
        List<Long> dataIds = new ArrayList<>();
        if(jsonList!=null){
            for(JSONObject json : jsonList){
                dataIds.add(json.getLongValue("dataId"));
            }
        }
        return dataIds;
    }

}
